<script setup>
import {onMounted, ref, shallowReactive, shallowRef} from 'vue'
import ReplyWrapper from "@/views/salon/cmpts/ReplyWrapper.vue";
import {getPostCommentsWithReplies, getPostContent, like, saveComment, saveReply} from "@/api/post";
import {ElMessage} from "element-plus";
import {SUCCESS} from "@/core/constants/HttpStatus";
import {useUserStore} from "@/store";
import {renderContent} from "@/utils/renderUtil";

const {postId} = defineProps({
  postId: Number,
})
//console.log('@props', postId)
const userStore = useUserStore();
//console.log(userStore.userInfo)
// 登录者信息
const {unickname} = userStore.userInfo;

const postViewData = shallowRef({
  id: '',
  uid: '',
  unickname: '',
  title: '',
  content: '',
  type: 0,
  releaseTime: '',
  imageUrl: [],
  imageUrls: [],
  comments: '',
});
const commentViewList = ref([]);
const textareaRef = ref(null);
// 区分评论和回复
let isComment = ref(true);
let commentText = ref('');
// 回复的评论对象
let commentItem = shallowRef({});
// 帖子评论当前页面
let currentPage = ref(1);
// 滑动到底部的回复框
const scrollToTextarea = () => {
  textareaRef.value.scrollIntoView({behavior: "smooth"});
}
//底部输入框重置
const resetCommentText = () => {
  commentText.value = '';
};
// 发起评论
const doReply = (_isComment, {commentId, tounickname}) => {
  textareaRef.value.scrollIntoView({behavior: "smooth"});
  isComment.value = _isComment;
  // console.log(textareaRef)
  commentItem.value = {
    commentId,
    tounickname
  }
};
const submitComment = async () => {
  const res = await saveComment({
    unickname: unickname,
    content: commentText.value,
    pid: postId
  })
  return res.data;
}
const submitReply = async () => {
  const {commentId, tounickname} = commentItem.value;
  const res = await saveReply({
    content: commentText.value,
    fromunickname: unickname,
    tounickname: tounickname,
    cid: commentId
  });
  console.log(res)
  return res.data;
}
// 提交评论
const handleReply = async () => {
  // 根据上下文判断是回复帖子还是回复评论
  try {
    const data = isComment.value ? await submitComment() : await submitReply();
    const {code, msg} = data;
    console.log(data)
    if (code != SUCCESS) {
      throw new Error(msg || "123");
    }
    ElMessage.success(msg || "回复成功");
    // 重置comment标志
    isComment.value = true;
    await fetchCommentsWithReplies();
  } catch (e) {
    ElMessage.error(e.message || "评论失败");
  }

  // 清空输入区域
  resetCommentText();
};

// 展开评论
const showMoreReplies = (commentId) => {
  console.log('aaa')
  commentViewList.value.map(item=>{
    if(item.id === commentId) {
      item.hasFlatten = true;
    }
  })
};

//帖子点赞数前端传参
const doLike = async (objType, objId) => {
  try {
    const res = await like({
      unickname,objType,objId,
    });
    const {code, msg} = res.data;
    if(Number(code) !== SUCCESS) {
      throw new Error(msg);
    }
    ElMessage.success(msg || "点赞成功");
    await fetchCommentsWithReplies();
  } catch (e) {
    ElMessage.error(e?.message || "点赞失败");
  }
};

const fetchCommentsWithReplies = async () => {
  console.log('fetch')
  try {
    const res = await getPostCommentsWithReplies({postId, currentPage: currentPage.value});
    const {code,data,msg} = res.data;
    if(Number(code) !== SUCCESS) {
      throw new Error(msg);
    }
    commentViewList.value = data.map(item=>{
      item.hasFlatten=false;
      return item;
    });
  } catch (e) {
    ElMessage.error(e?.message || "获取评论失败");
  }
};

const loadContentAndComments = async () => {
  try {
    const res = await getPostContent({postId});
    const res2 = await getPostCommentsWithReplies({postId, currentPage: currentPage.value})
    const {code, data, msg} = res.data;
    if (SUCCESS !== Number(code)) {
      throw new Error(msg);
    }
    data.imageUrl = JSON.parse(data.imageUrl);
    postViewData.value = data;
    commentViewList.value = res2.data.data;
  } catch (e) {
    ElMessage.error(e.message || "帖子内容获取失败")
  }
};
// 切换评论页面
const handleCurrentChange = (val) => {
  console.log(val)
  currentPage.value = val;
  loadContentAndComments();
};

onMounted(() => {
  loadContentAndComments();
})

</script>
<template>
  <div class="post-view">
    <div class="type-topic">创意交流</div>
    <div class="post-view-head">
      <div class="title-header">发帖详情</div>
    </div>
    <div class="post-view-body">
      <div class="view-body-top">
        <div class="post-avatar">
          <div class="firstName-avatar" id="poster">
            <span>{{ postViewData.unickname ? postViewData.unickname.charAt(0) : '' }}</span>
          </div>
        </div>
        <div class="post-info">
          <span class="nickname">{{ postViewData.unickname }}</span>
          <span class="release-time">发布于{{ postViewData.releaseTime }}</span><br><br>
        </div>
      </div>
      <div class="view-body-content">
        <div class="rich-text" v-html="renderContent(postViewData.content)"></div>
        <div class="img-wrapper" :class="postViewData.imageUrl?.length !== 1 && 'notSingle'">
          <div v-for="(url, idx) in postViewData.imageUrl" :key="idx">
            <img
                :src="url"
                alt=""
                class="postContentImg"
            />
          </div>
<!--          <img v-for="(url, idx) in postViewData.imageUrl" :key="idx" :src="url"-->
<!--               alt="" />-->
        </div>

        <div class="reply-btn">
          <button @click="scrollToTextarea" class="postReplyBtn">回复</button>
        </div>
      </div>
    </div>
    <ReplyWrapper
        :total="Number(postViewData.comments)"
        :comment-view-list="commentViewList"
        :handle-current-change="handleCurrentChange"
        :do-reply="doReply"
        :do-like="doLike"
        :show-more-replies="showMoreReplies"
        :render-content="renderContent"
    />
    <div class="reply-box">
      <div class="reply-avatar">
        <div class="firstName-avatar">{{ unickname?.charAt(0) }}</div>
      </div>
      <div class="input-area">
        <textarea class="reply-inp-box" v-model="commentText" ref="textareaRef"></textarea>
        <div class="letter-num-tip">还能输入{{ 1000 - commentText.length }}字</div>
        <div class="button-area">
          <div @click="handleReply" class="reply btn">
            <i class="iconfont icon-huifu"></i>回复
          </div>
          <div @click="resetCommentText" class="reset btn">
            <i class="iconfont icon-zhongzhi"></i>重置
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="less" scoped>
.img-wrapper {
  &.notSingle {
    display: grid;
    grid-template-columns: repeat(3, auto);
    justify-items: center;
  }
  //gap: 20px;
  & > div {
    height: 200px;
  }
  // 帖子图片样式
  .postContentImg {
    height: 100%;
    object-fit: contain;
  }
}

.type-topic {
  font-size: 32px;
  font-weight: 550;
  border-bottom: 1px solid black;
  line-height: 60px;
  width:96%;
}

.title-header {
  padding-left: 15px;
  margin: 10px 0;
  background-color: #def4fd;
  font-size: 18px;
  line-height: 30px;
  width:95%;
}

.firstName-avatar {
  border-radius: 50%;
  width: 100%;
  height: 100%;
  background-color: #a5e6f1;
  border: 0.5px solid rgb(86, 85, 85);
  font-size: 25px;
  box-sizing: border-box;
  text-align: center;
}

.nickname {
  font-size: 14px;
  font-weight: 550;
  //font-family: 'SimSun';
}

.post-view-body {
  width: 95%;
  .view-body-top {
    height: 45px;
    margin-bottom: 10px;
    overflow: hidden;

    .post-avatar {
      width: 45px;
      height: 45px;
      float: left;
      line-height: 45px;

      .firstName-avatar {
        background-color: #7fc4ef;
      }
    }

    .post-info {
      float: left;
      line-height: 45px;
      margin-left: 20px;

      .nickname {
        font-size: 20px;
      }

      .release-time {
        margin-left: 10px;
        font-size: 12px;
        color: #b7b5b5;
      }
    }
  }

  .view-body-content {
    position: relative;
    padding: 10px 0 10px 60px;

    .rich-text {
      min-height: 50px;
    }

    .reply-btn {
      overflow: hidden;

      .postReplyBtn {
        float: right;
        background-color: white;
        border: 1px solid black;
        width: 70px;
        text-align: center;
        height: 25px;
        cursor: pointer;
        border-radius: 15px;
      }
    }
  }
}

.reply-box {
  position: relative;
  padding-left: 60px;
  margin-top: 40px;

  .reply-avatar {
    width: 40px;
    height: 40px;

    .firstName-avatar {
      line-height: 40px;
      background-color: #7fc4ef;
    }

    position: absolute;
    top: 0;
    left: 0;
  }

  .input-area {
    border: 1px solid #b7b5b5;
    padding: 8px;

    .reply-inp-box {
      width: 100%;
      min-height: 100px;
      border: none;
      outline: none;
      resize: none;
      white-space: break-spaces;
      font-size: 20px;
      line-height: 1.1;
    }

    .letter-num-tip {
      font-size: 12px;
      color: #b7b5b5;
    }
  }

  .btn {
    cursor: pointer;
    width: 80px;
    height: 20px;
    border-radius: 10px;
    border: 1px solid black;
    line-height: 20px;
    text-align: center;
    position: relative;
    display: inline-flex;
    align-items: center;
    justify-content: center;
  }

  .button-area {
    display: flex;
    align-items: center;
    gap: 20px;
    margin-top: 6px;
  }
}

</style>
